<?php
require("dbFunctions.php");

/**
 * Adds a new Supplier to the database
 * This file should be hidden from users using the web interface and is used to populate the database
 * from the mobile device specifically.
 *
 * Author: Steve Gennaoui
 * Date: 10/24/2012
 */

//Get the parameters
$first_name = $_REQUEST['fname'];
$last_name = $_REQUEST['lname'];
$email = $_REQUEST['email'];
$is_admin = $_REQUEST['is_admin'];
$admin_password = $_REQUEST['admin_password'];

//current condition are non-null.
// If the email is not a valid email, filter_var returns false.
if( is_null($first_name) )
	die("First name is not provided.");
if( is_null($last_name) )
	die("Last name is not provided.");
if( !filter_var($email,FILTER_VALIDATE_EMAIL) )
	die("Email is not in a valid format.");
if( is_null($is_admin) )
	die("Supplier was not identified as administrator or non-administrator.");
if( ($is_admin == 1 && is_null($admin_password)) )
	die("Supplier was identified as administrator, but no password was provided.");

$email = strtolower($email);
$pw_hash = hash("sha256",$admin_password);

//If they are not an admin, guarantee they have a null password
if( $is_admin == 0 )
	$pw_hash = null;

//Get a PDO Database connection
$dbh = connectDB();

//Construct the query to add a new supplier
// Ignore the is_active field so that the default value True is used
$query =  "INSERT INTO Suppliers (first_name,last_name,email,is_admin,admin_password) VALUES (:fname,:lname,:email,:is_admin,:admin_password)";

//Check to if the email has already been entered and is activated.
if(getIDByEmail($email, "Suppliers") > 0)
	die("$email has already beed added.");

//Check to see if this email has already been entered and is merely deactivated.
// If so, then just re-activate the Supplier.
$sup_id = getIDByEmail($email,"Suppliers",1);

if( $sup_id > 0 )
{
	$query = "UPDATE Suppliers SET is_active=1 WHERE sup_id=:sup_id";
	$stmt = $dbh->prepare($query);
	$stmt->bindParam(':sup_id',$sup_id);
	$stmt->execute();
	exit("Reactivated supplier with email: $email");
}

//Create a PDO Statement by preparing the query
$stmt = $dbh->prepare( $query );

//Bind parameters to avoid SQL injection
$stmt->bindParam(':fname', $first_name);
$stmt->bindParam(':lname', $last_name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':is_admin', $is_admin);
$stmt->bindParam(':admin_password', $pw_hash);

//Execute the PDO Statement
$stmt->execute();

//Release the PDO Statement and PDO database connection
$stmt = null;
$dbh = null;

?>
